﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;

/*
 *    功能:
 *         1.加载Resources/Prefabs目录下的预制体文件到场景中显示
 *
 *    说明:
 *         1.使用Unity继承Monobehaviour实现单例模式,使用时需将代码挂载到游戏物体,一般建议是摄像机
 *
 *
 *    创建时间:2019-7-6 02:47:02
 *    修改时间:2019-7-6 02:47:11
 * 
 */

public class LoadPrefab : MonoBehaviour
{
    public static LoadPrefab Instance;

    private void Awake()
    {
        Instance = this;
    }

    /// <summary>
    /// 加载预制体到,并返回对象,没有找到对应资源返回null.
    /// 可加载任意类型预制体,物体预制体,音效预制体,图片预制体
    /// </summary>
    /// <param name="path">Resources/Prefabs/目录下资源路径 ,不需要加Prefabs; 如Prefabs/Game/Cube需被加载,填写路径为Game/Cube</param>
    /// <param name="show">是否到场景显示,如果音频等资源不需显示则填写false</param>
    /// <param name="parentPath">父物体路径,不填或者填空则不设置父物体;使用GameObject.Find()方法查找,如果填写的父物体不存在,则显示到场景顶层</param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public T LoadPrefab2Scenes<T>(string path, bool show, string parentPath = null) where T : Object
    {
        //加载资源
        T prefab = Resources.Load<T>("Prefabs/" + path);
        if (prefab == null)
        {
            return null;
        }

        //如果是不需要显示的资源则直接返回
        if (!show)
        {
            return prefab;
        }

        //实例化预制体
        GameObject obj = Instantiate(prefab) as GameObject;
        obj.name = prefab.name;

        //设置位置及其缩放大小后返回对象

        Transform parent = null;
        if (!string.IsNullOrEmpty(parentPath))
        {
            parent = GameObject.Find(parentPath).transform;
        }

        obj.transform.parent = parent;
        obj.transform.localRotation = Quaternion.identity;
        obj.transform.localPosition = Vector3.zero;
        obj.transform.localScale = Vector3.one;
        //将其转换为想要返回的类型,未测试,一般是GameObject类型
        return obj as T;
    }
}